package com.teradata.dashboard.ui.fragment;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.ActionBar.OnNavigationListener;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.teradata.dashboard.R;
import com.teradata.dashboard.utils.HttpUtil;

public class KpiFragment extends Fragment {

	/**
	 * 用于对Fragment进行管理
	 */
	private int tabTImport = 0;
	private int tabTGuimo = 1;
	private int tabTYingli = 2;
	private int tabTFengxian = 3;
	private int tabTKaohe = 4;
	private int tabTTongye = 5;
	private JSONArray categorys;
	private Menu categoryMenu;

	public static  final String SELECTED_CATEGORY_ID = "SELECTED_CATEGORY_ID";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View messageLayout = inflater.inflate(R.layout.kpi, container, false);
		System.out.println("kpi input");
		getOverflowMenu();
		return messageLayout;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		getActivity().getActionBar().setDisplayShowTitleEnabled(false);
		getActivity().getActionBar().setNavigationMode(
				ActionBar.NAVIGATION_MODE_STANDARD);
		getActivity().getActionBar().setDisplayShowHomeEnabled(false);
		// getActivity().getActionBar().setHomeButtonEnabled(false);
		// getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
		try {
			/*
			 * System.out.println(DashboardApplication.app.getCookieManager().
			 * getCookie(DashboardConstant.getPara("COOKIEURL", "")));
			 */
			System.out.println("--------请求kpi前----------");
			queryKpiCategory();
			System.out.println("--------请求kpi后----------");
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	// 获取kpiCategory列表
	private void queryKpiCategory() throws Exception {	
		// 定义发送请求的URL
		String url ="dashboard/listCategoryByUser.action";
		System.out.println("queryKpiCategory");
		HttpUtil.post(url, new RequestParams(), new JsonHttpResponseHandler(){
			 @Override
           public void onSuccess(int statusCode, Header[] headers,JSONObject response) {
				 System.out.println("queryKpiCategory success");
				try {
					if(response.getJSONArray("data")!=null){
						categorys=response.getJSONArray("data");
						buildMenu(categoryMenu);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }			 
		});		
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		categoryMenu=menu;
		System.out.println("onCreateOptionsMenu1"+menu.size());
		if(categorys!=null){
			buildMenu(menu);
		}
		System.out.println("onCreateOptionsMenu2"+menu.size());
	}

	private void buildMenu(Menu menu) {
		menu.clear();
		for(int i = 0; i<categorys.length(); i++)
		{
			 Map<String, String> m = new HashMap<String, String>();
			 JSONObject data=null;
			try {
				data = categorys.getJSONObject(i);
				 m.put("kpiCategoryName", data.getString("kpiCategoryName"));
		         m.put("kpiCategoryId", data.getString("kpiCategoryId"));		        
		         menu.add(0, i, i, data.getString("kpiCategoryName")).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		System.out.println("buildMenu"+menu.size());
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		System.out.println("onPrepareOptionsMenu1"+menu.size());
		if(menu.size()<2&&categorys!=null){
			buildMenu(menu);
		}
		System.out.println("onPrepareOptionsMenu2"+menu.size());
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			showKpiList(((JSONObject)categorys.getJSONObject(item.getItemId())).getString("kpiCategoryId"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return super.onOptionsItemSelected(item);
	}

	private void showKpiList(String categoryId) {
		KpiListFragment fragment = new KpiListFragment();
		Bundle args = new Bundle();
		args.putString(SELECTED_CATEGORY_ID, categoryId);
		fragment.setArguments(args);
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		ft.replace(R.id.kpiListContainer, fragment);
		ft.commit();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(SELECTED_CATEGORY_ID, getActivity().getActionBar()
				.getSelectedNavigationIndex());
	}

	private void getOverflowMenu() {

		try {
			ViewConfiguration config = ViewConfiguration
					.get(this.getActivity());
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			if (menuKeyField != null) {
				menuKeyField.setAccessible(true);
				menuKeyField.setBoolean(config, false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
     * 实现 ActionBar.OnNavigationListener接口
     */
    class CategorySelectListenser implements OnNavigationListener
    {        /* 当选择下拉菜单项的时候，将Activity中的内容置换为对应的Fragment */
        @Override
		public boolean onNavigationItemSelected(int itemPosition, long itemId)
        {
        	
    		try {    			
    			String categoryId= categorys.getJSONObject(itemPosition).getString("kpiCategoryId");
    			showKpiList(categoryId);
    		} catch (JSONException e1) {
    			// TODO 自动生成的 catch 块
    			e1.printStackTrace();
    		}
        	
            return true;
        }
    }
    
    class KpiCategoryAdapter extends BaseAdapter {
    //自定义图片Adapter以内部类形式存在于MainActivity中，方便访问MainActivity中的各个变量，特别是imgs数组
               private Context context;//用于接收传递过来的Context对象
               public KpiCategoryAdapter(Context context) {
                   super();
                   this.context = context;
               }


               /* (non-Javadoc)
                * @see android.widget.Adapter#getCount()
                */
               @Override
               public int getCount() {
                   return categorys.length();
               }

               /* (non-Javadoc)
                * @see android.widget.Adapter#getItem(int)
                */
               @Override
               public Object getItem(int position) {
                
            	try {
					return categorys.getJSONObject(position);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
               }

               /* (non-Javadoc)
                * @see android.widget.Adapter#getItemId(int)
                */
               @Override
               public long getItemId(int position) {
                   return position;//categorys.getJSONObject(position).getString("kpiCategoryId");
               }

               /* (non-Javadoc)
                * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
                */
               @Override
               public View getView(int position, View convertView, ViewGroup parent) {
            	   
            	   LayoutInflater inflater =LayoutInflater.from(context);
                   convertView =inflater.inflate(R.layout.kpi_acb,null);
                   if(convertView!=null){
                           TextView titleView=(TextView)convertView.findViewById(R.id.acbar_kpiCategory_title);
                           TextView countView=(TextView)convertView.findViewById(R.id.acbar_kpiCategory_count);
                           
                           try {
                        	   titleView.setText(((JSONObject)getItem(position)).getString("kpiCategoryName"));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
                           countView.setText("10");
                   }                 
                   return convertView;                 
               }
           }
}
